<?php
class home extends base{
  function __construct()
  {
    parent::__construct();
    // 没 config 文件 ，则进入安装流程
    global $db_config;
    if(!isset($db_config)){
      $this->install();
      exit;
    }
    $domain = strtolower($_SERVER['HTTP_HOST']);
    // 安装系统之前无法链接数据库，下面代码会有误
    $site = load('m/site_m')->get(" and domain = '".$domain."'");
    $sid = $site[0]['uuid']?:'default';
    $this->site = $site[0];
    define('SID', $sid);
  }

  function index()
  {
    $this->page('home');
  }

  private function install()
  {
    global $db_config;
    if(is_array($db_config))redirect("?/");
    if($_POST){
      $db = new db($_POST);
      // 测试数据库连接
      if (!$db->link) {
        redirect("?/", '数据库连接失败，请检查配置');
      }
      
      // 检查数据库是否存在
      $result = $db->query("SHOW DATABASES LIKE '".$_POST['default_db']."'");
      if (empty($result)) {
        // 尝试创建数据库
        try {
          $db->query("CREATE DATABASE ".$_POST['default_db']." DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
        } catch (Exception $e) {
          redirect("?/", '数据库创建失败，请检查用户权限');
        }
        
        // 选择新创建的数据库
        $db->query("USE ".$_POST['default_db']);
      }

      $sql_file = APP.($_POST['setdemo'] ? 'demo.sql' : 'basic.sql');
      $sql = file_get_contents($sql_file);
      $db->muti_query($sql);
      $base_dir = rtrim($_POST['base_dir'],'/').'/';
      $seed = randstr();
      file_put_contents(APP.'config_user.php','<?php 
define(\'BASE\',\''.$base_dir.'?/\');
define(\'ADMIN_BASE\',BASE.\'?/admin/\');
define(\'SEED\',\''.$seed.'\');
$db_config = array(
  \'host\'      =>\''.$_POST['host'].'\',
  \'user\'      =>\''.$_POST['user'].'\',
  \'password\'  =>\''.$_POST['password'].'\',
  \'default_db\'=>\''.$_POST['default_db'].'\'
);');
      redirect($_POST['base_dir'],'安装成功');
    }
    else {
      header("Content-type: text/html; charset=utf-8");
      $param['page_title'] = '安装Alpaca4.0';
      $param['base'] = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
      $param['rewrite'] = 0;
      if (function_exists('apache_get_modules')) {
        $param['rewrite'] = in_array('mod_rewrite', apache_get_modules()) ? 1 : 0;
      } else if (getenv('HTTP_MOD_REWRITE') == 'On') {
        $param['rewrite'] = 1;
      }
      $param['writable'] = ($this->is_writable('../app') && $this->is_writable('../app/v')) ? 1 : 0;
      $this->display("v/home/install",$param);
    }
  }

  private function is_writable($file) {
    if (is_dir($file)){
      $dir = $file;
      if ($fp = @fopen("$dir/test.txt", 'w')) {
        @fclose($fp);
        @unlink("$dir/test.txt");
        $writeable = 1;
      } else {
        $writeable = 0;
      }
    } else {
      if ($fp = @fopen($file, 'a+')) {
        @fclose($fp);
        $writeable = 1;
      } else {
        $writeable = 0;
      }
    }

    return $writeable;
  }

  function page($url = 'home'){
    global $tags;
    $node = load('m/node_m')->n('tags');

    $itms = _decode($node['ext']);
    if (is_array($itms)) {
        foreach($itms as $it){
            $name = $it['name'];
            $tags[$name]=$it['val'];
        }
    }

    $pages = load('m/node_m')->get(" and sid='".SID."' and  `name`='$url'");
    //获取下级页面
    $page = $pages[0];
    if (empty($page)) {
        // 处理页面不存在的情况
        die('页面不存在');
        // 或者重定向到404页面
        // redirect('/404');
    }

    $pid = $page['uuid'];
    $children = load('m/node_m')->get(" and sid='".SID."' and  `upid`='$pid'");


    $nchildren = array();
    if (is_array($children)) {
        foreach($children as $child){
            $meta = _decode($child['meta']);
            if (is_array($meta)) {
                $nchildren[] = array_merge($meta,$child);
            }
        }
    }


    $meta = _decode($page['meta']);
    $meta = is_array($meta) ? $meta : array();
    $param = array_merge($page,$meta);
    $param['children'] = $nchildren;
    $template = $template_default = 'v/layout/template';
    if($this->site['template'])$template = 'v/template/'.$this->site['template'];
    if($meta['template'])$template = 'v/template/'.$meta['template'];
    if (!is_file($template)) $template = $template_default;
    $layout = $meta['layout']?'v/template/'.$meta['layout']:'v/layout/layout';
    $param['al_content'] = view($layout,$param,true);
    $param['page_title'] =$param['page_title'] ?:$param['title'];
    $param['meta_keywords'] = $param['keywords']?:$param['title'];
    $param['meta_description'] = $param['description']?:$param['title'];
    view($template,$param);
  }


  function reg(){
    $conf = array('email'=>'required|email','username'=>'required|isexist','password'=>'required');
    $err = validate($conf);
    if($_POST['password']!=$_POST['repassword']){
      $err['password']='两次密码不一样';
      $param['val'] = $_POST;
      $param['err'] = $err;
      $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '注册';
      $this->display('v/user/register',$param);
    }elseif( $err === TRUE) {
      load('m/user_m')->register();
        redirect(BASE,'注册成功，请登录。');
    }else {
        $param['val'] = $_POST;
        $param['err'] = $err;
        $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '注册';
        $this->display('v/user/register',$param);
    }
  }

  function login(){
    $user = load('m/user_m');
    $rtu = isset($_GET['rtu'])?$_GET['rtu']:'/';
    $conf = array('username'=>'required','password'=>'required');
    $err = validate($conf);
    if (is_array($err)) {
      $err['info'] = $this->m->login_err;
      $param['err'] = $err;
      $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '登录';
      $this->display('v/user/login',$param);
      exit;
    }

    if( $user->login( $_POST['username'] , $_POST['password'] )){
      redirect($rtu,'登录成功！');
      exit;
    }
    // 认证失败
    redirect('/login/?rtu='.$rtu, $user->login_err);
  }

  function logout(){
  	load('m/user_m')->logout();
    redirect(BASE,'退出登录！');
  }
}

function alpa($elem,$layout = 'list')
{
  global $tags;
  if(array_key_exists($elem,$tags))return $tags[$elem];

  $layout = $layout?'v/layout/'.$layout:'';
  //$node = is_numeric($elem)?load('m/node_m')->get($elem):
  $nodes = load('m/node_m')->get(" and name='$elem' and sid = '".SID."'");
  $node = $nodes[0];

  switch($node['type']){
    case 'link':
      $itms = _decode($node['ext']);
      return view($layout,array('itms'=>$itms),true);
      break;

    case 'page':
      $rs = load('m/node_m')->get(" and upid = '$node[id]' order by `order`,`id` asc");
      foreach($rs as $r){
        $itms[] = array('name'=>'p/'.$r['name'].'/','title'=>$r['title']);
      }
      return view($layout,array('itms'=>$itms),true);
      break;
  }
}


function alpa_list($elem,$layout = 'list')
{

  global $tags;
  if(array_key_exists($elem,$tags))return $tags[$elem];

  $layout = $layout?'v/layout/'.$layout:'';

  $node = is_numeric($elem)?load('m/node_m')->get($elem):load('m/node_m')->n($elem);
  $node_id = $node['id'];
  $node_sid = $node['sid'];
  $list = load('m/node_m')->get(" and `upid` = '$node_id' and `sid` = '$node_sid' order by `order`,`update_date` desc");
  foreach ($list as $k => $v) {
    $list[$k]['meta'] = _decode($v['meta']);
  }
  return view($layout,array('lists'=>$list),true);
}
